from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.sku_image import SKUImageSerializer, SKUSerializer
from meiduo_admin.utils.paginator import PageNum


class SKUImageView(ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = SKUImage.objects.all()
    serializer_class = SKUImageSerializer
    pagination_class = PageNum

    def simple(self, request):
        skus = SKU.objects.all()
        ser = SKUSerializer(instance=skus, many=True)

        return Response(ser.data)

    # def create(self, request, *args, **kwargs):
    #     """
    #     因为默认的方法中没有启用fast_dfs写入图片，所以重写存储图片方法
    #     """
    #     # 获取数据
    #     data = request.data
    #
    #     # 校验数据
    #     ser = self.get_serializer(data=data)
    #     ser.is_valid()
    #
    #     # 存储图片
    #     client = Fdfs_client(settings.FDFS_CONFIG)
    #     res = client.upload_by_buffer(ser.validated_data.get('image').read())  # 内存中的数据要用read方法读取
    #     if res['Status'] != 'Upload successed.':  # 存储失败
    #         return Response({'errmsg': '存储图片失败'})
    #
    #     # 将数据保存到数据库
    #     sku = SKUImage.objects.create(sku=ser.validated_data.get('sku'), image=res.get('Remote file_id'))
    #     return_ser = SKUImageSerializer(sku)
    #
    #     # 返回响应
    #     return Response(return_ser.data)

